<template>
    <div class="device-add-wrap">
        <el-dialog :title="$t('device.device-edit.148398-84')" :visible.sync="open" width="900px">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item :label="$t('device.device-edit.148398-1')" prop="deviceName">
                            <el-input style="width: 300px" v-model="form.deviceName" :placeholder="$t('device.device-edit.148398-2')"></el-input>
                        </el-form-item>
                        <el-form-item label="" prop="productName">
                            <template slot="label">
                                <span style="color: red">*</span>
                                {{ $t('device.device-edit.148398-4') }}
                            </template>
                            <el-input style="width: 300px" readonly v-model="form.productName" :placeholder="$t('device.device-edit.148398-5')">
                                <el-button slot="append" @click="selectProduct()">{{ $t('device.device-edit.148398-6') }}</el-button>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="" prop="serialNumber">
                            <template slot="label">
                                <span style="color: red">*</span>
                                {{ $t('device.device-edit.148398-7') }}
                            </template>
                            <el-input style="width: 300px" v-model="form.serialNumber" :placeholder="$t('device.device-edit.148398-8')" maxlength="32" :readonly="form.deviceType === 3">
                                <el-button v-if="form.deviceType !== 3" slot="append" @click="generateNum" :loading="genDisabled" v-hasPermi="['iot:device:add']">
                                    {{ $t('device.device-edit.148398-9') }}
                                </el-button>
                                <el-button v-if="form.deviceType === 3" slot="append" @click="genSipID()" v-hasPermi="['iot:device:add']">
                                    {{ $t('device.device-edit.148398-9') }}
                                </el-button>
                            </el-input>
                            <el-alert v-if="openServerTip" class="alert-wrap" type="info" show-icon :description="$t('device.device-edit.148398-10')"></el-alert>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item :label="$t('device.device-edit.148398-12')" prop="firmwareVersion">
                            <el-input style="width: 300px" v-model="form.firmwareVersion" :placeholder="$t('device.device-edit.148398-13')" type="number" step="0.1" :disabled="form.deviceType === 3">
                                <template slot="prepend">Version</template>
                                <template slot="append">{{ form.firmwareType === 1 ? $t('firmware.index.222541-52') : $t('firmware.index.222541-53') }}</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item :label="$t('device.device-edit.148398-19')" prop="locationWay">
                            <el-select style="width: 300px" v-model="form.locationWay" :placeholder="$t('device.device-edit.148398-20')">
                                <el-option v-for="dict in dict.type.iot_location_way" :key="dict.value" :label="dict.label" :value="Number(dict.value)" />
                            </el-select>
                        </el-form-item>
                        <!-- 设备影子 -->
                        <el-form-item v-if="form.deviceType !== 3" :label="$t('device.device-edit.148398-15')" prop="isShadow">
                            <el-radio-group v-model="form.isShadow">
                                <el-radio :label="1">{{ $t('device.device-edit.148398-85') }}</el-radio>
                                <el-radio :label="0">{{ $t('device.device-edit.148398-86') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="submitForm" type="primary">{{ $t('device.product-list.058448-14') }}</el-button>
                <el-button @click="closeDialog">{{ $t('device.product-list.058448-15') }}</el-button>
            </div>
        </el-dialog>
        <!-- 选择产品 -->
        <product-list ref="productList" :productId="form.productId" @productEvent="getProductData($event)" />
        <!-- 监控设备生成通道id -->
        <sipid ref="sipidGen" :product="form" @addGenEvent="getSipIDData($event)" />
    </div>
</template>

<script>
import productList from './product-list';
import sipid from '../sip/sipidGen.vue';
import { getProduct } from '@/api/iot/product';
import { addDevice, generatorDeviceNum } from '@/api/iot/device';

export default {
    name: 'DeviceAdd',
    dicts: ['iot_device_status', 'iot_location_way'],
    components: {
        productList,
        sipid,
    },

    data() {
        return {
            open: false,
            // 生成设备编码是否禁用
            genDisabled: false,
            // 遮罩层
            loading: true,
            deviceId: '',
            // 表单参数
            form: {
                productId: 0,
                status: 1,
                locationWay: 1,
                firmwareType: 1,
                firmwareVersion: 1,
                serialNumber: '',
                deviceType: 1,
                isSimulate: 0,
                isShadow: 0,
            },
            openTip: false,
            openServerTip: false,
            serverType: 1,
            // 表单校验
            rules: {
                deviceName: [
                    {
                        required: true,
                        message: this.$t('device.device-edit.148398-60'),
                        trigger: 'blur',
                    },
                    {
                        min: 2,
                        max: 32,
                        message: this.$t('device.device-edit.148398-61'),
                        trigger: 'blur',
                    },
                ],
                firmwareVersion: [
                    {
                        required: true,
                        message: this.$t('device.device-edit.148398-62'),
                        trigger: 'blur',
                    },
                ],
            },
        };
    },
    computed: {
        deviceStatus: {
            set(val) {
                if (val == 1) {
                    // 1-未激活，2-禁用，3-在线，4-离线
                    this.form.status = 2;
                } else if (val == 0) {
                    this.form.status = 1;
                }
            },
            get() {
                if (this.form.status == 2) {
                    return 1;
                }
                return 0;
            },
        },
    },
    created() {},
    methods: {
        /**选择产品 */
        selectProduct() {
            this.$refs.productList.open = true;
            this.$refs.productList.getList();
        },
        /**获取选中的产品 */
        getProductData(product) {
            this.form.productId = product.productId;
            this.form.productName = product.productName;
            this.form.deviceType = product.deviceType;
            this.form.protocolCode = product.protocolCode;
            this.form.tenantId = product.tenantId;
            this.form.tenantName = product.tenantName;
            this.form.firmwareType = product.firmwareType;
            if (product.deviceType == 3) {
                this.form.locationWay = 3;
            } else {
                this.form.locationWay = 1;
            }
            if (product.transport === 'TCP') {
                this.openServerTip = true;
                this.serverType = 3;
            } else {
                this.openServerTip = false;
                this.serverType = 1;
            }
        },
        // 生成随机字母和数字
        generateNum() {
            if (!this.form.productId || this.form.productId == 0) {
                this.$modal.alertError(this.$t('device.device-edit.148398-72'));
                return;
            }
            this.genDisabled = true;
            const params = { type: this.serverType };
            generatorDeviceNum(params).then((response) => {
                this.form.serialNumber = response.data;
                this.genDisabled = false;
            });
        },
        // 生成监控设备ID
        genSipID() {
            this.$refs.sipidGen.open = true;
        },
        //生成通道id
        getSipIDData(devsipid) {
            this.$set(this.form, 'serialNumber', devsipid);
        },
        /** 获取产品信息 */
        getProduct() {
            getProduct(this.form.productId).then((response) => {
                this.form = response.data;
                this.changeProductCode(this.form.protocolCode);
            });
        },
        // 表单重置
        reset() {
            this.form = {
                deviceId: 0,
                deviceName: null,
                productId: null,
                productName: null,
                userId: null,
                userName: null,
                tenantId: null,
                tenantName: null,
                serialNumber: '',
                firmwareType: 1,
                firmwareVersion: 1,
                status: 1,
                rssi: null,
                networkAddress: null,
                networkIp: null,
                longitude: null,
                latitude: null,
                activeTime: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                locationWay: 1,
                clientId: 0,
                isShadow: 0,
            };
            this.deviceStatus = 0;
            this.resetForm('form');
        },
        /** 提交按钮 */
        submitForm() {
            if (this.form.serialNumber == null || this.form.serialNumber == 0) {
                this.$modal.alertError(this.$t('device.device-edit.148398-65'));
                return;
            }
            let reg = /^[0-9a-zA-Z]+$/;
            if (!reg.test(this.form.serialNumber)) {
                this.$modal.alertError(this.$t('device.device-edit.148398-66'));
                return;
            }
            if (this.form.productId == null || this.form.productId == 0) {
                this.$modal.alertError(this.$t('device.device-edit.148398-67'));
                return;
            }
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    addDevice(this.form).then((response) => {
                        if (response.code == 200) {
                            this.$message.success('设备添加成功');
                            if (this.form.status == 2) {
                                this.deviceStatus = 1;
                            }
                            this.$parent.getList();
                            this.open = false;
                        } else {
                            this.$message.error(response.msg);
                        }
                    });
                }
            });
        },
        /**关闭对话框 */
        closeDialog() {
            this.open = false;
        },
    },
};
</script>

<style lang="scss" scoped>
.device-add-wrap {
    .alert-wrap {
        height: 35px;
        margin-top: 10px;

        ::v-deep .el-alert__icon {
            font-size: 16px;
            width: 16px;
        }

        ::v-deep .el-alert__description {
            font-size: 12px;
            margin: 0;
        }
    }
}
</style>
